#ifndef A9BF0322_18D4_4DAD_92FB_951DB0439C07
#define A9BF0322_18D4_4DAD_92FB_951DB0439C07

#include <iostream>
#include <sys/epoll.h>
#include "Socket.hpp"
#include "Log.hpp"
#include "Epoller.hpp"
#include <memory>

uint32_t EVENT_IN = (EPOLLIN);
uint32_t EVENT_OUT = (EPOLLOUT);

class Epollserver : nocopy
{

    static const int num = 64;

public:
    Epollserver(uint16_t port)
        : port_(port),
          _listensocket_ptr(new Socket()),
          _epoller_ptr(new Epoller())
    {
    }

    ~Epollserver()
    {
        _listensocket_ptr->Close();
    }

    void Init()
    {
        _listensocket_ptr->InitSocket();
        _listensocket_ptr->Bind(port_);
        _listensocket_ptr->Listen();

        lg(Info, "create listen socket success: %d\n", _listensocket_ptr->Fd());
    }

    void Accepter()
    {
        // 获取了一个新连接
        string clientip;
        uint16_t clientport;
        int sock = _listensocket_ptr->Accept(&clientip, &clientport);  //成功连接， 然后将新获得的sock添加到关心事件中，即rb_tree中。
        if (sock > 0)
        {
            // 我们能直接读取吗？不能， 因为获取新连接和事件就绪不一样
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, sock, EVENT_IN);
            lg(Info, "get a new link, client info@ %s:%d", clientip.c_str(), clientport);
        }
    }

    void Recver(int fd)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1); 
        if (n > 0)
        {
            buffer[n] = 0;

            cout << "get a message: " << buffer << endl;



            //write
            string echo_str = "server echo $ ";
            echo_str += buffer;
            write(fd, echo_str.c_str(), echo_str.size());

        }
        else if (n == 0)  //等待超时，
        {
            lg(Info, "client quit, me too, close fd is : %d", fd);
            
            //读时间已经关了， 就不需要关心了， 就移除事件
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }
        else
        {
            lg(Waring, "recv error: fd is : %d", fd);   
            
            _epoller_ptr->EpollerUpdate(EPOLL_CTL_DEL, fd, 0);
            close(fd);
        }

    }

    void Dispatcher(struct epoll_event revs[], int n)
    {
        for (int i = 0; i < n; i++)
        {
            // 知道了哪个文件描述符的哪个事件就绪了。处理所有的就绪的事件
            uint32_t event = revs[i].events;
            int fd = revs[i].data.fd;

            //判断就绪条件
            if (event & EVENT_IN)
            {
                if (fd == _listensocket_ptr->Fd())   //监听fd就绪， 获取了一个新链接
                {
                    Accepter();
                }
                else  // 其他fd上面的普通读取事件就绪
                {
                    Recver(fd);
                }
            }

        }
    }

    void Start()
    {
        // 将listensock添加到epoll中 -> listensock和他关心的事件， 添加到内核epoll模型中rb_tree中。 
        _epoller_ptr->EpollerUpdate(EPOLL_CTL_ADD, _listensocket_ptr->Fd(), EVENT_IN);
        struct epoll_event revs[num];

        for (;;)
        {
            int n = _epoller_ptr->EpollerWait(revs, num);   //EpollerWait等待函数封装

            if (n > 0)
            {
                // 有事件就绪， 那么第0号下标一定是有数据的
                lg(Debug, "event happend, fd is : %d", revs[0].data.fd);

                Dispatcher(revs, n);
            }
            else if (n == 0)
            {
                lg(Info, "time out ...");
            }
            else
            {
                lg(Error, "epoll wait error");
            }
        }
    }



private:
    shared_ptr<Socket> _listensocket_ptr;
    shared_ptr<Epoller> _epoller_ptr;

    uint16_t port_;
};

#endif /* A9BF0322_18D4_4DAD_92FB_951DB0439C07 */
